package me.linkcn.ydtxl.web.resource;

import freemarker.template.Configuration;
import me.linkcn.ydtxl.web.Application;
import me.linkcn.ydtxl.web.objects.Error;
import me.linkcn.ydtxl.web.objects.Redirect;
import org.restlet.data.MediaType;
import org.restlet.ext.freemarker.TemplateRepresentation;
import org.restlet.ext.jackson.JacksonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ServerResource;

import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: cmcc
 * Date: 11-8-16
 * Time: 下午7:58
 */
public class BaseResource extends ServerResource {
    protected final Application application;

    public BaseResource() {
        super();
        application = (Application) getApplication();
    }

    protected String getServerUri() {
        return application.getServerUri();
    }

    private Configuration getFmcConfiguration() {
        return application.getFmc();
    }

    protected Representation getHTMLTemplateRepresentation(String templateName,
                                                           Map<String, Object> dataModel) {
        // The template representation is based on Freemarker.
        return new TemplateRepresentation(templateName, getFmcConfiguration(),
                dataModel, MediaType.TEXT_HTML);
    }

    protected Representation generateErrorRepresentation(String errorMessage, String errorCode) {
        JacksonRepresentation result = null;
        // This is an error
        // Generate the output representation
        try {
            Error error = new Error();
            error.setErrorMessage(errorMessage);
            error.setErrorCode(errorCode);
            result = new JacksonRepresentation(error);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    protected Representation generateRedirectRepresentation(String url) {
        JacksonRepresentation result = null;
        // This is an redirect
        // Generate the output representation
        try {
            Redirect redirect = new Redirect();
            redirect.setUrl(url);
            result = new JacksonRepresentation(redirect);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}
